package com.yqg.demo.task;

import lombok.Data;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * @author suzhuang
 * @ClassName: TalkSend
 * @Function: TODO
 * @Date: 2023/5/9 20:41
 */
@Data
public class TalkSend implements Runnable{
    DatagramSocket socket=null;
    BufferedReader reader =null;

    private String toIP;
    private int toPort;
    private String message;


    public TalkSend(String toIP,int toPort,String message){
        this.toIP=toIP;
        this.toPort=toPort;
        this.message=message;

        try{
            socket=new DatagramSocket();    //建立套接字
            reader = new BufferedReader(new InputStreamReader(System.in));//从控制台读取数据
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true) {
            try{
                //将数据转换为byte字节
                byte[] datas=message.getBytes(StandardCharsets.UTF_8);
                DatagramPacket packet=new DatagramPacket(datas,0,datas.length,new InetSocketAddress(this.toIP,this.toPort));
                socket.send(packet);    //发送数据包
                if(message.equals("bye")){
                    break;    //监测到结束指令
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        socket.close();
    }
}

